#!/bin/bash

# 安装脚本依赖软件包
sudo apt install -y build-essential gcc-arm-linux-gnueabihf bc flex bison libyaml-dev libssl-dev libncurses-dev

# 解压缩内核源码
if [ ! -d "fsmp1a-linux-5.4.31" ]; then
    tar -axf fsmp1a-linux-5.4.31.tar.xz
fi

# 导入默认配置
cp defconfig fsmp1a-linux-5.4.31/arch/arm/configs/fsmp1a_extended_defconfig
make -C fsmp1a-linux-5.4.31 fsmp1a_extended_defconfig ARCH=arm O=../build

# 修改设备树
cp -v dts/* fsmp1a-linux-5.4.31/arch/arm/boot/dts

# 修改编译配置
# make -C fsmp1a-linux-5.4.31 menuconfig ARCH=arm O=../build
# make -C fsmp1a-linux-5.4.31 savedefconfig ARCH=arm O=../build
# cp build/defconfig .

# 编译内核
make -C fsmp1a-linux-5.4.31 -j$(nproc) zImage ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- O=../build

# 编译并安装内核模块
make -C fsmp1a-linux-5.4.31 -j$(nproc) modules ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- O=../build
make -C fsmp1a-linux-5.4.31 -j$(nproc) modules_install INSTALL_MOD_PATH=../modules ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- O=../build
rm -f modules/lib/modules/5.4.31/build modules/lib/modules/5.4.31/source

# 编译设备树
make -C fsmp1a-linux-5.4.31 dtbs ARCH=arm O=../build

# 复制内核镜像和设备树
cp build/arch/arm/boot/zImage .
cp build/arch/arm/boot/dts/stm32mp157a-fsmp1a-extended-mipi050.dtb fsmp1a.dtb

# 复制文件到系统镜像目录
cp -v zImage fsmp1a.dtb ../bullseye/files/boot
cp -rv modules/lib ../bullseye/files/
